#pragma once
#include "Lock.hpp"
#include <filesystem> //C++17
#include <string>
#include <fstream>
#include <cstdio>
#include <sys/types.h>
#include <unistd.h>
namespace LogModule
{
    class LogStrategy
    {
    public:
        const std::string gsep = "\r\n";
        LogStrategy()
        {
        }
        ~LogStrategy()
        {
        }
        virtual void SyncLog(const std::string &messager) = 0;
    };

    // 实现向显示器打印：
    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        void SyncLog(const std::string &messager) override
        {
            LockGuard lockGuard(_mutex);
            std::cout << messager << std::endl;
        }

    private:
        Mutex _mutex;
    };

    const std::string defaultpath = "./";
    const std::string defaultname = "my.log";
    // 向特定文件进行打印
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string path = defaultpath, const std::string file = defaultname)
            : _file(file), _path(path)
        {
            _file_name = _path + (_path.back() == '/' ? "" : "/") + _file;
            // 判断文件是否存在
            if (std::filesystem::exists(_path))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }
        void SyncLog(const std::string &messager) override
        {
            // 向文件中打印：
            LockGuard lock(_mutex);
            std::ofstream out(_file_name, std::ios::app);
            out << messager << gsep;
            out.close();
        }
        ~FileLogStrategy()
        {
        }

    private:
        Mutex _mutex;

        // 文件路径与文件名：
        std::string _file;
        std::string _path;

        std::string _file_name;
    };

    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };
    std::string GetLevel(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "None";
        }
    }
    std::string GetTime()
    {
        time_t curr = time(nullptr);
        struct tm curr_tm;
        localtime_r(&curr, &curr_tm);
        char timebuffer[128];
        snprintf(timebuffer, sizeof(timebuffer), "%4d-%02d-%02d %02d:%02d:%02d",
                 curr_tm.tm_year + 1900,
                 curr_tm.tm_mon + 1,
                 curr_tm.tm_mday,
                 curr_tm.tm_hour,
                 curr_tm.tm_min,
                 curr_tm.tm_sec);
        return timebuffer;
    }
    class Logger
    {
    public:
        Logger()
        {
            EnConsoleLogStrategy();
        }
        void EnFileLogStrategy()
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>();
        }
        void EnConsoleLogStrategy()
        {
            _fflush_strategy = std::make_unique<ConsoleLogStrategy>();
        }
        class LogMessager
        {
        public:
            LogMessager(LogLevel &level, std::string &src_file, int line_num, Logger &logger)
                : _curr_time(GetTime()),
                  _src_file(src_file),
                  _line_num(line_num),
                  _id(getpid()),
                  _level(GetLevel(level)),
                  _logger(logger)
            {
                std::stringstream ss;
                ss << "[" << _curr_time << "] "
                   << "[" << _level << "] "
                   << "[" << _id << "] "
                   << "[" << _src_file << "] "
                   << "[" << _line_num << "] "
                   << "- ";
                _log_info = ss.str();
            }

            template <class T>
            LogMessager &operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _log_info += ss.str();
                return *this;
            }

            ~LogMessager()
            {
                if (_logger._fflush_strategy)
                {
                    _logger._fflush_strategy->SyncLog(_log_info);
                }
            }

        private:
            std::string _curr_time;
            std::string _src_file;
            int _line_num;
            pid_t _id;
            std::string _log_info;
            std::string _level;
            Logger &_logger;
        };

        // 返回临时对象不能用引用
        LogMessager operator()(LogLevel level, std::string name, int line)
        {
            return LogMessager(level, name, line, *this);
        }
        ~Logger()
        {
        }

    private:
        std::unique_ptr<LogStrategy> _fflush_strategy;
    };

    // 全局日志对象
    Logger logger;

// 使用宏，简化用户操作，获取文件名和行号
#define LOG(level) logger(level, __FILE__, __LINE__)
}
